#import "UserProfile.h"
#import "TeamProfile.h"
#import "JSON/JSON.h"

#define kViewTag				1		// for tagging our embedded controls for removal at cell recycle time

#define kFriendSection			0		// for selecting the table section containing friends
#define kTeamSection			1		// for selecting the table section containing teams

#define ROW_HEIGHT_FOR_TABLE	30

static NSString *kSectionTitleKey = @"sectionTitleKey";
static NSString *kSourceKey = @"sourceKey";
static NSString *kViewKey = @"viewKey";


@implementation UserProfile

@synthesize userId;
@synthesize displayNameLabel, emailLabel, userProfileTableView;
@synthesize friends, teams, profile;
@synthesize tableSourceArray;
@synthesize appDelegate;


- (void)viewDidLoad{
    [super viewDidLoad];

//	NSLog(@"Entering UserProfile viewDidLoad\n");
//	NSLog(@"UserProfile.userId is %d", userId);
	
	self.appDelegate = (playSerengetiMobile1AppDelegate *)[[UIApplication sharedApplication] delegate];
	
	responseData = [[NSMutableData data] retain];
	NSString *URLString = [NSString stringWithFormat:@"%@user/%d/json", appDelegate.baseURL, userId];
//	NSLog(@"Submit String for UserProfile is %@\n", URLString);
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];
	[[NSURLConnection alloc] initWithRequest:request delegate:self];
	
	self.friends = [[NSMutableArray alloc] init];
	self.teams = [[NSMutableArray alloc] init];
	self.tableSourceArray = [NSArray arrayWithObjects:
							 [NSDictionary dictionaryWithObjectsAndKeys:
							  @"Friends", kSectionTitleKey,
							  self.friends, kSourceKey,
							  nil],
							 
							 [NSDictionary dictionaryWithObjectsAndKeys:
							  @"Teams", kSectionTitleKey,
							  self.teams, kSourceKey,
							  nil],
							 nil];
	
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

#pragma mark -
#pragma mark populateViewDataMethods

-(void)populateViewData:(NSDictionary *)parsedData{
	NSDictionary *userDictionary = [parsedData objectForKey:@"user"];
	NSMutableArray *friendArray =[parsedData objectForKey:@"friends"];
	NSMutableArray *teamArray = [parsedData objectForKey:@"teams"];
	
	[self populateUser:(NSDictionary *)userDictionary];
	[self populateFriends:(NSMutableArray *)friendArray];
	[self populateTeams:(NSMutableArray *)teamArray];
	
	[self.userProfileTableView reloadData];
}

- (void)populateUser:(NSDictionary *)userDictionary{
//	NSLog(@"Entering populateUser.\n");
	profile = [[User alloc] init];
	
	profile.email = [userDictionary objectForKey:@"email"];
	profile.name = [userDictionary objectForKey:@"name"];
	
	displayNameLabel.text = profile.name;
	emailLabel.text = profile.email;
}

- (void)populateFriends:(NSMutableArray *)friendArray{
//	NSLog(@"Entering populateFriends.\n");
//	NSLog(@"friendArray contains %d elements.\n", [friendArray count]);
	if([friendArray count] == 0){
		//Do something
	} else {
		[friends removeAllObjects];
		int i;
		for (i = 0; i < [friendArray count]; i++){
			User *friend = [[User alloc] init];
			NSDictionary *friendsDic = [friendArray objectAtIndex:i];
			friend.userId = [[friendsDic objectForKey:@"id"] integerValue];
			friend.name = [friendsDic objectForKey:@"name"];
//			NSLog(@"Adding friend %d, %@ to friends.\n", friend.userId, friend.name);
			[friends addObject: friend];
		}
	}
}

- (void)populateTeams:(NSMutableArray *)teamArray{
//	NSLog(@"Entering populateTeams.\n");
//	NSLog(@"teamArray contains %d elements.\n", [teamArray count]);
	if([teamArray count] == 0){
		//Do something
	} else {
		[teams removeAllObjects];
		int i;
		for (i = 0; i < [teamArray count]; i++){
			Team *team = [[Team alloc] init];
			NSDictionary *teamDic = [teamArray objectAtIndex:i];
			team.teamId = [[teamDic objectForKey:@"id"] integerValue];
			team.teamName = [teamDic objectForKey:@"name"];
//			NSLog(@"Adding team %d, %@ to team.\n", team.teamId, team.teamName);
			[teams addObject: team];
		}
	}
}

#pragma mark -
#pragma mark NSURLConnectionDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	displayNameLabel.text = [NSString stringWithFormat:@"Connection failed: %@\n", [error description]];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	[connection release];
	
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//	NSLog(@"responseString reads: %@\n", responseString);
	
	[responseData release];
	
	NSDictionary *parsedData = [responseString JSONValue];
	
	[responseString release];
	
	if (parsedData == nil) {
		displayNameLabel.text = [NSString stringWithFormat:@"Error in returned data.\n"];
	} else {
		[self populateViewData:(NSDictionary *)parsedData];
	}
}	

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return [tableSourceArray count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	return [[self.tableSourceArray objectAtIndex: section] valueForKey:kSectionTitleKey];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//	NSLog(@"Entering tableView:%@ numberOfRowsInSection:%d", tableView, section);
	NSMutableArray *sectionData = [[self.tableSourceArray objectAtIndex:section] valueForKey:kSourceKey];
//	NSLog(@"number of expected rows: %d.\n", [sectionData count]);
	return [sectionData count];
}

// to determine specific row height for each cell, override this.
// In this example, each row is determined by its subviews that are embedded.
//
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return ROW_HEIGHT_FOR_TABLE;
	//return ([indexPath row] == 0) ? 50.0 : 38.0;
}

// to determine which UITableViewCell to be used on a given row.
//
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell *cell = nil;
	User *aUser;
	Team *aTeam;
	
	if(indexPath.section == kFriendSection){
		aUser = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
	} else if (indexPath.section == kTeamSection){
		aTeam = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
	}
	
	static NSString *kDisplayCell_ID = @"DisplayCellID";
	cell = [self.userProfileTableView dequeueReusableCellWithIdentifier:kDisplayCell_ID];
	if (cell == nil)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kDisplayCell_ID] autorelease];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
	}
	else
	{
		// the cell is being recycled, remove old embedded controls
		UIView *viewToRemove = nil;
		viewToRemove = [cell.contentView viewWithTag:kViewTag];
		if (viewToRemove){
			[viewToRemove removeFromSuperview];
		}
	}
	
	UIControl *control = [[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kViewKey];
	[cell.contentView addSubview:control];
	
	if(indexPath.section == kFriendSection){
		cell.textLabel.text = aUser.name;
	}else if(indexPath.section == kTeamSection){
		cell.textLabel.text = aTeam.teamName;
	}
	
	return cell;
}

- (void)switchAction:(id)sender
{
	// NSLog(@"switchAction: value = %d", [sender isOn]);
}

- (void)pageAction:(id)sender
{
	// NSLog(@"pageAction: current page = %d", [sender currentPage]);
}

#pragma mark -
#pragma mark UITableViewDelegate

// the table's selection has changed, switch to that item's UIViewController
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	
	User *aUser;
	Team *aTeam;
	
	if(indexPath.section == kFriendSection){
		aUser = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
		 
		UserProfile *aUserProfileView = [[UserProfile alloc] initWithNibName:@"UserProfile" bundle:nil];
		aUserProfileView.userId = aUser.userId;
		[self.view addSubview:aUserProfileView.view];
		
	} else if (indexPath.section == kTeamSection){
		aTeam = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
		
		TeamProfile *aTeamProfileView = [[TeamProfile alloc] initWithNibName:@"TeamProfile" bundle:nil];
		aTeamProfileView.teamId = aTeam.teamId;
		[self.view addSubview:aTeamProfileView.view];
	}
	
}

@end
